﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Dosimetria.Security
{
    public static class Encryption
    {
        /// <summary>
        /// Metodo estatico que encripta a SHA1 un String
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string encryptSHA1(string value)
        {
            Byte[] bytes = System.Text.Encoding.Unicode.GetBytes(value);
            System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();

            Byte[] hash = sha1.ComputeHash(bytes);

            return System.Convert.ToBase64String(hash);
        }

        /// <summary>
        /// Desencripta con AES un valor string
        /// </summary>
        /// <param name="value">Valor encriptado que se va a desencriptar</param>
        /// <param name="key">Llave privada para desencriptar</param>
        /// <returns><c>value</c> desencriptado con AES</returns>
        public static string decryptAES(string value, string key)
        {
            System.Security.Cryptography.RijndaelManaged AES = new System.Security.Cryptography.RijndaelManaged();
            Byte[] _value = null;
            string result;

            _value = System.Convert.FromBase64String(value);

            key = Encryption.encryptSHA1(key).PadRight(32, '=');
            AES.Key = System.Text.Encoding.ASCII.GetBytes(key);
            AES.IV = System.Text.Encoding.ASCII.GetBytes(key.Substring(12, 16));

            result = System.Text.Encoding.UTF8.GetString(AES.CreateDecryptor().TransformFinalBlock(_value, 0, _value.Length));
            AES.Clear();
            return result;
        }
    }
}